from util.Route import after,before,error,getUsername,getUserRemoteAddr
from flask import request,Response,json
from service import AuthService,LogManageService
from util import JwtUtil
from common.R import R
from util.ProcessUtil import pool

@before
def interceptor():
    r = AuthService.pathNotNeedAuth(request)
    if r==True:
        return
    if r==None:
        return R.create(303,None,"用户登陆信息已过期请重新登录")
    if r==False:
        return R.reject("你无权访问接口"+request.path)
    
@after
def after_request_handler(res: Response):
    # 定义默认的值
    path = request.path
    excluded_start_path = ['/public']
    for start_path in excluded_start_path:
        if path.startswith(start_path):
            return res
    
    status = res.status_code
    # 如果不在排除列表中，执行特定的操作
    token = request.headers.get("Authorization")
    ip = getUserRemoteAddr()
    username = getUsername()
    if(username == None):
        try:
            username = json.loads(request.data)
            username = username.get('username')
        except:
            username = 0
    resp = res.json # 获取响应数据，并指定为文本
    if(resp == None):
        resp = {}
    req = {
        "body":request.get_data().decode('utf-8'),
        "param":request.args.to_dict()
    }
    pool.submit(LogManageService.addLog, username, token, resp, status, ip, path,req,request.method)
    return res  # 注意：必须返回响应对象，以便继续将其发送给客户端


# @error(Exception)
# def errHandle(e):
#     return R.server_error(),500

@error(404)
def notFound(e:Exception):
    return R.not_found(request.path),404
